﻿namespace Home.Wcf
{
    using System;
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using System.Linq;
    using System.Linq.Expressions;
    using System.ServiceModel;
    using System.ServiceModel.Channels;
    using System.ServiceModel.Description;
    using System.ServiceModel.Dispatcher;
    using System.Text;
    using System.Threading.Tasks;

    [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
    public class WcfErrorHandlingBehaviorAttribute : Attribute, IServiceBehavior
    {
        public string Namespace { get; set; }

        public Type ErrorHandlerType { get; set; }

        public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
        {
            var handler = default(IErrorHandler);
            if (this.ErrorHandlerType != null)
            {
                handler = (IErrorHandler)TypeHelper.Create(this.ErrorHandlerType);
                var defaultHandler = handler as WcfErrorHandler;
                if (defaultHandler != null && string.IsNullOrEmpty(defaultHandler.Namesapce) && !string.IsNullOrEmpty(this.Namespace))
                {
                    defaultHandler.Namesapce = this.Namespace;
                }
            }
            else
            {
                handler = new WcfErrorHandler() { Namesapce = this.Namespace };
            }

            foreach (var dispatcher in serviceHostBase.ChannelDispatchers)
            {
                var channelDispatcher = dispatcher as ChannelDispatcher;
                if (channelDispatcher != null)
                {
                    channelDispatcher.ErrorHandlers.Add(handler);
                }
            }
        }

        public void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, Collection<ServiceEndpoint> endpoints, BindingParameterCollection bindingParameters)
        {
        }

        public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
        {
        }
    }
}
